﻿using System.Collections.Generic;
using Microsoft.Crm.Sdk.Metadata;
using Microsoft.Crm.SdkTypeProxy.Metadata;

namespace TransactionServer.CRM4Activities
{
    class CRM4EntityMetadataCache : Dictionary<string, EntityMetadata>
    {
        CRM4Connector connector = null;
        private object syncRoot = new object();

        public CRM4EntityMetadataCache(CRM4Connector connector)
        {
            this.connector = connector;
        }

        public EntityMetadata this[string key] 
        { 
            get
            {
                lock (syncRoot)
                {
                    if (!base.ContainsKey(key))
                    {
                        var rerq = new RetrieveEntityRequest { EntityItems = EntityItems.IncludeAttributes | EntityItems.IncludeRelationships,LogicalName = key };
                        var rersp = (RetrieveEntityResponse)connector.metaCrmService.Execute(rerq);
                           
                        base[key] = rersp.EntityMetadata;
                    }
                    return base[key];
                }
            } 
        }
    }
}
